package ytmc.setup;

import org.apache.commons.configuration.*;
import org.apache.commons.configuration.tree.DefaultExpressionEngine;


/**
 *
 * @author Kicok
 */
public class Config
{
    private static final String CONFIG_FILENAME = "config.xml";

    private static XMLConfiguration instance;
    static
    {
        DefaultExpressionEngine engine = new DefaultExpressionEngine();
        engine.setPropertyDelimiter( "." );
        engine.setIndexStart( "{" );
        engine.setIndexEnd( "}" );
        engine.setAttributeStart( "@" );
        engine.setAttributeEnd( null );

        XMLConfiguration.setDefaultExpressionEngine( engine );
    }


    public static XMLConfiguration load()
    {
        if( !isConfigLoaded() )
        {
            try
            {
                instance = new XMLConfiguration( CONFIG_FILENAME );
                instance.setEncoding("UTF-8");
                instance.setAutoSave( false );
            }
            catch( ConfigurationException e )
            {
                System.out.println( "Załadowanie pliku konfiguracyjnego nie powiodło się" );
            }
        }

        return instance;
    }

    public static XMLConfiguration reload()
    {
        if( isConfigLoaded() )
        {
            try
            {
                instance.clear();
                instance.load();
            }
            catch( ConfigurationException e )
            {
                System.out.println( "Załadowanie pliku konfiguracyjnego nie powiodło się" );
            }
        }

        return load();
    }

    public static void save()
    {
        if( isConfigLoaded() )
        {
            try
            {
                instance.save();
            }
            catch( ConfigurationException e )
            {
                System.out.println( "Zapisanie konfiguracji nie powiodło się" );
            }
        }
    }

    private static boolean isConfigLoaded()
    {
        return instance instanceof Configuration;
    }


    private Config() { }
}